<?php

class FormFilter extends FormComponent
{

  /**
   * @var string
   */
  public $field;

  /**
   * @var string
   */
  public $foreignKey;

  /**
   * @var string
   */
  public $primaryKey;

  /**
   * @var boolean
   */
  public $required = false;

  /**
   * @var boolean
   */
  public $visible = true;

  /**
   * @var string
   */
  public $redirect;

  /**
   * @var array
   */
  public $redirectParams;

  /**
   * @var mixed
   */
  protected $value;

  public function execute()
  {
    $value = s::request()->get($this->getPrimaryKey());

    $this->setValue($value);

    s::response()->getParams()->set($this->getPrimaryKey(), $value);
  }

  public function render()
  {
    $this->set('name', $this->getPrimaryKey());
    $this->set('value', $this->getValue());
    $this->set('action', $action);
    $this->set('title', $this->title);
    $this->set('visible', $this->visible);

    return $this->getView()->render();
  }

  public function injectQueryParams(&$params)
  {
    $val = $this->getValue();

    if (empty($val) && $this->required) {
      s::getInstance()->warnings('Select the ' . $this->getTitle());
      s::response()->redirect(array($this->redirect, $this->redirectParams));
    }

    if (! empty($val) || $this->required) {
      $key = $this->getForeignKey();

      $params['where'][] = "$key = :$key";
      $params['data'][$key] = $val;
      $params['fields'][] = $key;
    }
  }

  /**
   * get field name
   */
  public function getField()
  {
    if (empty($this->field)) {
      $this->field = Inflector::underscore($this->getName());
    }

    return $this->field;
  }

  public function getPrimaryKey()
  {
    if (empty($this->primaryKey)) {
      $this->primaryKey = $this->getField();
    }

    return $this->primaryKey;
  }

  public function getForeignKey()
  {
    if (empty($this->foreignKey)) {
      $this->foreignKey = $this->getField();
    }

    return $this->foreignKey;
  }

  public function getValue()
  {
    return $this->value;
  }

  public function setValue($value)
  {
    $this->value = $value;
  }

  public function setDataFromPost(&$row, $post, $action)
  {
    $row[$this->getField()] = $this->value;
  }

  protected function getDisplayValue(&$row)
  {
    return $this->getValue($row);
  }

  protected function getRowValue(&$row)
  {
    return $row[$this->getField()];
  }

  protected function setRowValue(&$row)
  {
    $row[$this->getField()] = $this->value;
  }

  protected function getFieldValue(&$row, $name)
  {
    return $row[$name];
  }

  public function getTemplate()
  {
    $template = parent::getTemplate();

    if (empty($template)) {
      global $config;

      $template = $config['views_dir'] . '/form/form_filter_view.php';
    }

    return $template;
  }

}

?>